*Settings----------------------------------
set scheme plotplain


/*Notes-------------------------------------------------------------------------
This code is adapted from replication code for Berry et al. 2019 JEP
*-----------------------------------------------------------------------------*/

*Parameters--------------------------------------------------------------------
local exch=2288 //Exchange rate TSH per USD

local check_matching_shinacheck=1 //Set to 1 in order to drop the shina that are missing at least 1 treatment group (i.e. 2,6, and 14)
    *check_matching_shinacheck if shina overlap matters

	
*Create estimating datasets from BDM-------------------------------------------
use "${sdir}/Owners_cln.dta", clear
keep shina_id plot_id shina_plot_id s9_q_1

if "`check_matching_shinacheck'"=="1"{
	drop if shina_id==14 | shina_id==6 | shina_id==2
}

replace s9_q_1=s9_q_1/`exch'

drop if missing(s9_q_1)==1
pctile wtp_pctiles=s9_q_1, nq(100)
keep wtp_pctiles
keep if missing(wtp_pctiles)==0
gen n=_n

save "temp/wtp_pctiles.dta", replace


*Create estimating datasets from Leader Prediction-----------------------------
use "${sdir}/Leaders_and_Owners_cln.dta", clear
keep if owner_observed==1 //Keep for same individuals as BDM
keep shina_leader_plot_id shina_leader_id shina_plot_id leader_id shina_id plot_id q42_ldr trt_grp full_cost_obl

if "`check_matching_shinacheck'"=="1"{
	drop if shina_id==14 | shina_id==6 | shina_id==2
}

replace q42_ldr=q42_ldr/`exch'
replace full_cost_obl=full_cost_obl/`exch'

*Each treatment separately
foreach t in 0 1 2{
	preserve
	keep if trt_grp_ldr==`t'
	pctile ldr`t'_pctiles=q42_ldr, nq(100)
	keep ldr`t'_pctiles
	keep if missing(ldr`t'_pctiles)==0
	gen n=_n

	save "temp/ldr`t'_pctiles.dta", replace
	restore
	}
	
*do based on full cost
preserve
bysort shina_plot_id: gen check=_n
keep if check==1
drop check

pctile fee_pctiles=full_cost_obl, nq(100)
keep fee_pctiles
keep if missing(fee_pctiles)==0
gen n=_n

save "temp/fee_pctiles.dta", replace
restore



*make q-q plots-----------------------------------------------------------------
use "temp/wtp_pctiles.dta", clear

merge 1:1 n using "temp/ldr0_pctiles.dta", nogen
merge 1:1 n using "temp/ldr1_pctiles.dta", nogen
merge 1:1 n using "temp/ldr2_pctiles.dta", nogen
merge 1:1 n using "temp/fee_pctiles.dta", nogen

foreach t in 0 1 2{
	twoway ///
			(scatter ldr`t'_pctiles wtp_pctiles) ///
			(function y=x, range(wtp_pctiles)), ///
			yscale(range(0 830)) ylabel(0(100)800) legend(off)
	graph export "figures/qqplot_ldr`t'.png", replace	 
}
twoway ///
		(scatter fee_pctiles wtp_pctiles) ///
		(function y=x, range(wtp_pctiles)), ///
		yscale(range(0 830)) ylabel(0(100)800) legend(off)
graph export "figures/qqplot_fee.png", replace	 



*End------
clear





